<template>
  <div class="body_all">
    <el-form
      :rules="rules"
      ref="form"
      class="form"
      :model="form"
      label-width="100px"
    >
      <el-form-item label="栏目：" required prop="cid">
        <el-select
          ref="selectTree"
          v-model="form.cid"
          placeholder="请选择栏目"
          style="width: 400px"
          clearable
          @clear="handleClear"
        >
          <el-option :value="form.cid" :label="form.cidName" hidden />
          <el-tree
            ref="tree"
            :data="columnModelList"
            :props="{
              label: 'name',
              children: 'childlist',
            }"
            show-checkbox
            check-strictly
            node-key="id"
            :default-checked-keys="[defaultChecked]"
            :default-expanded-keys="[defaultChecked]"
            @check-change="handleCheckChange"
            style="height: auto; overflow: auto"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="商品标题：">
        <el-input
          class="a_title"
          :maxlength="20"
          :show-word-limit="true"
          v-model="form.title"
          placeholder="请输入内容"
        ></el-input>
        <span class="a_span">不超过20字</span>
      </el-form-item>
      <el-form-item label="商品主图：">
        <div class="commodityImgCss">
          <div
            class="imageUl"
            v-for="(item, index) in form.thumbUrl"
            :key="index"
          >
            <div style="position: relative">
              <img :src="item" class="avatar" />
              <i
                class="el-icon-error el-img-error"
                @click="delImage(index)"
              ></i>
            </div>
          </div>
          <el-upload
            v-show="5 > form.thumbUrl.length"
            class="avatar-uploader"
            action
            :limit="5"
            :before-upload="uploadBf"
            :http-request="ImgSuccess"
            :show-file-list="false"
            accept="image/*"
          >
            <i class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </div>
        <div class="a_span">
          要求：最多5张、尺寸为800*800，不大于15M、PNG、JPG格式件图片
        </div>
      </el-form-item>
      <el-form-item label="商品售价：">
        <el-input
          class="money_input"
          v-model="form.price"
          placeholder="请输入内容"
        ></el-input>
        <span class="a_money_span">元</span>
      </el-form-item>
      <el-form-item label="市场价格：">
        <el-input
          class="money_input"
          v-model="form.mk_price"
          placeholder="请输入内容"
        ></el-input>
        <span class="a_money_span">元</span>
      </el-form-item>
      <el-form-item label="商品详情：" style="margin-bottom: 0px">
      </el-form-item>
    </el-form>
    <div class="foot_editor">
      <wangeditor
        class="editor"
        ref="editor"
        name="editor"
        :textData="content"
      ></wangeditor>
    </div>
    <div class="foot_btn">
      <el-button type="primary" @click="onSubmit">保存</el-button>
      <el-button @click="closebtn">取消</el-button>
    </div>
  </div>
</template>

<script>
import wangeditor from "../../components/wangeditor"; //　wangeditor富文本插件　－使用中
import { UrlPath } from "../../utils/util";
export default {
  components: {
    wangeditor,
  },
  data() {
    var column = (rule, value, callback) => {
      if (value === "") {
        return callback(new Error("请选择栏目"));
      } else {
        callback();
      }
    };
    return {
      rules: {
        cid: [{ validator: column, trigger: "change" }],
      },
      pidStart: false,
      form: {
        id: "",
        sort: 1, // 排序
        cid: "",
        cidName: "",
        title: "",
        keywords: "",
        desp: "",
        thumb: [],
        thumbUrl: [],
        price: "",
        mk_price: "",
        content: "",
        new: "",
        top: "",
        show: "",
      },
      content: "", // 富文本
      // 栏目类型
      defaultChecked: "",
      columnModelList: [],
    };
  },
  beforeRouteEnter: (to, from, next) => {
    if (to.query.id === undefined) {
      to.meta.title = "添加商品";
    } else {
      to.meta.title = "编辑商品";
    }
    next();
  },
  created() {
    this.getMode();
    if (this.$route.query.id !== undefined) {
      this.form.id = this.$route.query.id;
      this.form.cid =
        this.$route.query.cid !== "" ? parseInt(this.$route.query.cid) : "";
      this.form.cidName = this.$route.query.cname;
      this.defaultChecked =
        this.$route.query.cid !== "" ? parseInt(this.$route.query.cid) : "";
      this.form.title = this.$route.query.title;
      this.form.keywords = this.$route.query.keywords;
      this.form.desp = this.$route.query.desp;
      // 解决不同属性相同空间数据同化问题
      let pemImg = [];
      for (let i = 0; i < this.$route.query.imgs.length; i++) {
        let parm = this.$route.query.imgs[i].replace(`${UrlPath}`, "");
        pemImg.push(parm);
      }
      this.form.thumb = pemImg;
      this.form.thumbUrl = this.$route.query.imgs;
      this.form.price = this.$route.query.price;
      this.form.mk_price = this.$route.query.mk_price;
      this.content = this.$route.query.content;
      this.form.new = this.$route.query.new;
      this.form.top = this.$route.query.top;
      this.form.show = this.$route.query.show;
      this.form.sort = this.$route.query.sort;
    } else {
      this.form = this.$options.data().form;
      this.content = this.$options.data().content;
    }
  },
  methods: {
    // 获取模型数据
    getMode() {
      this.$cmsapi
        .CommodityModel()
        .then((res) => {
          this.columnModelList = res.data;
          this.setTableIndex(this.columnModelList);
        })
        .catch((error) => {
          console.log(error);
        });
    },
    // 数据获取级别
    setTableIndex(arr, index) {
      arr.forEach((item, key) => {
        item.index = key + 1;
        if (index) {
          item.index = index + "-" + (key + 1);
        }
        if (item.childlist) {
          item.disabled = true;
          this.setTableIndex(item.childlist, item.index);
        }
      });
    },
    // 点击checkbox
    handleCheckChange(data, checked) {
      if (checked) {
        this.$refs.tree.setCheckedNodes([data]); // 设置目前节点勾选
        this.defaultChecked = data.id;
        this.form.cid = data.id;
        this.form.cidName = data.name;
      } else {
        if (this.form.cid === data.id) {
          this.handleClear();
        }
      }
      this.$refs.selectTree.blur();
    },
    // 清空
    handleClear(val) {
      if (!val || val === "") {
        this.$refs.tree.setCheckedNodes([]); // 设置目前节点勾选
        this.defaultChecked = "";
        this.form.cid = "";
        this.form.cidName = "";
      }
    },
    // 返回事件
    closebtn() {
      this.$router.go(-1);
    },
    // 表单提交
    onSubmit() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          let paramImg = [];
          for (let i = 0; i < this.form.thumb.length; i++) {
            let param1 = this.form.thumb[i].replace(`${UrlPath}`, "");
            paramImg.push(param1);
          }
          this.content = this.$refs.editor.submit();
          let param = {
            sort: this.form.sort,
            id: this.form.id,
            cid: this.form.cid,
            title: this.form.title,
            keywords: this.form.keywords,
            desp: this.form.desp,
            imgs: paramImg.length > 0 ? paramImg : "",
            price: this.form.price,
            mk_price: this.form.mk_price,
            content: this.content,
          };
          this.$cmsapi
            .CommoditySave(param)
            .then((res) => {
              if (res.code === 1) {
                this.$message({
                  type: "error",
                  message: "提交失败",
                });
              } else {
                this.$message({
                  type: "success",
                  message: "提交成功！",
                });
                this.$router.go(-1);
              }
            })
            .catch((erro) => {
              console.log(erro);
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 图片上传情况
    uploadBf(file) {
      const isJPG =
        file.type === "image/jpg" ||
        file.type === "image/jpeg" ||
        file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 15;
      if (!isJPG) {
        this.$message.error("上传商品图片只能是 JPG、JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传商品图片大小不能超过 15MB!");
      }
      return isJPG && isLt2M;
    },
    // 图片上传
    ImgSuccess(param) {
      this.$cmsapi.FileUpload(param.file).then((res) => {
        this.form.thumb.push(res.data.path);
        this.form.thumbUrl.push(res.data.url);
      }).catch((erro) => {
        console.log(erro);
      });
    },
    delImage(index) {
      this.form.thumb.splice(index, 1);
      this.form.thumbUrl.splice(index, 1);
    },
  },
};
</script>
<style scoped>
/* 表单 */
.form {
  width: 50%;
}
.a_title {
  width: 78%;
}
.commodityImgCss {
  display: flex;
  flex-flow: wrap;
}
.commodityImgCss div {
  margin-bottom: 10px;
}
.a_span {
  color: #cbcbcb;
  display: inline-block;
}
.money_input {
  width: 35%;
}
</style>>